package hu.uszeged.inf.stud.prf.todo.controller.user;

import hu.uszeged.inf.stud.prf.todo.controller.user.qualifier.LoggedInUser;
import hu.uszeged.inf.stud.prf.todo.controller.user.qualifier.UserDatabase;
import hu.uszeged.inf.stud.prf.todo.entity.user.User;

import java.io.Serializable;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

@SessionScoped
@Named
public class Login implements Serializable {

	private static final long serialVersionUID = -6501275750966617332L;

	@Inject
	Credentials credentials;

	@Inject
	@UserDatabase
	EntityManager userDatabase;

	private User user;
	
	private Long myActiveIndex;

	public String loginAction() {

		@SuppressWarnings("unchecked")
		List<User> results = userDatabase
				.createQuery(
						"select u from User u where u.name = :username and u.password = :password")
				.setParameter("username", credentials.getUsername())
				.setParameter("password", credentials.getPassword())
				.getResultList();

		if (!results.isEmpty()) {
			user = results.get(0);
		} else {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Invalid login name or password!"));
			return "/content/login?faces-redirect=false";
		}

		return "/index?faces-redirect=true";
		
	}

	public void setUser(User user){
		this.user = user;
	}
	
	
	public String logout() {
		user = null;
		return "/index?faces-redirect=true";
	}

	public boolean isLoggedIn() {
		return user != null;
	}
		
    public Long getMyActiveIndex() {
    	return myActiveIndex;
    }

	public void setMyActiveIndex(Long myActiveIndex) {
		this.myActiveIndex = myActiveIndex;
	}
	
	public String changeMyActiveIndex(Long myActiveIndex) {
        this.myActiveIndex = myActiveIndex;
        switch (myActiveIndex.intValue()) {
            case 0:
                return "/index?faces-redirect=true";
            case 1:
                return "/content/usertask/list?faces-redirect=true";
            case 2:
                return "/content/tasktype/list?faces-redirect=true";
            case 3:
                return "/content/resource/list?faces-redirect=true";
            case 4:
                return "/content/registration?faces-redirect=true";
            case 5:            	
                return "/content/login?faces-redirect=true";
            case 6:
            	logout();
            default:
                return "/index?faces-redirect=true";
        }
    }

	@Named
	@Produces
	@LoggedInUser
	User getCurrentUser() {
		return user;
	}

}
